package controllers;

import java.io.IOException;
import java.security.GeneralSecurityException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import models.UserModel;

import com.google.gdata.client.http.AuthSubUtil;
import com.google.gdata.util.AuthenticationException;

import entities.User;

public class AuthorizationAnalyticServlet extends HttpServlet{
	public void doGet(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException {
		String scope = "https://www.google.com/analytics/feeds/";
		String nextUrl = AuthSubUtil.getRequestUrl( request.getRequestURL().toString(), scope, false, true);
		
		String action = (String) request.getParameter("action");
		String username = request.getUserPrincipal().getName();
		UserModel userModel = UserModel.getInstance();
		User user = userModel.getUser(username);
		
		if (action != null) {
			if (action.equalsIgnoreCase("authorize")) {
				response.getWriter().println(nextUrl);
				response.sendRedirect(nextUrl);
				return ;
			} else if (user != null) {
				//Remove sessionToken
				user.setSessionToken(null);
				userModel.insert(user);
				
				//Redirect
				nextUrl = "/profile/view";
				response.sendRedirect(nextUrl);
				return ;
			}
		} else {
			// The user is being redirected back from google.com to exchange the AuthSub one time
		    // use token for a session token.
			String requestQuery = request.getQueryString();
			
			// Retrieve single use token from the URL.
		    String singleUseToken = AuthSubUtil.getTokenFromReply(requestQuery);
		    
		    //Get sessionToken
		    String sessionToken = ""; 
		    String authServiceError = "";
		    
		    if (singleUseToken != null) {
		        try {
		        	// Exchange single use token for session token.
		        	sessionToken =  AuthSubUtil.exchangeForSessionToken(singleUseToken, null);
		        } catch (AuthenticationException e) {
		        	authServiceError = e.getMessage();
		        } catch (GeneralSecurityException e) {
		        	authServiceError = e.getMessage();
		        } catch (IOException e) {
		        	authServiceError = e.getMessage();
		        }
			}
		    
		    if (!sessionToken.isEmpty() && user != null) {
		    	//Update sessionToken
		    	user.setSessionToken(sessionToken);
		    	userModel.insert(user);
		    	
		    	//Redirect
		    	nextUrl = "/process-analytic";
		    	response.sendRedirect(nextUrl);
		    	return ;
		    }
		    
		    if (!authServiceError.isEmpty()) {
		    	response.getWriter().println(authServiceError);
		    }
		}
	}
}
